package xyz.lwm.lazycat.web.proxy;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xyz.lwm.lazycat.annotation.Order;
import xyz.lwm.lazycat.utility.CollectionUtil;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.utility.PathUtil;
import xyz.lwm.lazycat.web.Controllable;
import xyz.lwm.lazycat.web.handle.Handler;
import xyz.lwm.lazycat.web.route.Route;
import xyz.lwm.lazycat.web.route.Router;
import xyz.lwm.lazycat.web.settings.ProxyHttpSetting;
import xyz.lwm.lazycat.web.settings.ProxySetting;

/**
 * <h3>代理收集</h3>
 * <p>说明:</p>
 * <pre>
 * 1. 如果想自行实现代理功能，可是实现 {@link Controllable} 接口, 并使用 {@link Router#proxy(String, Handler)} 或 {@link Router#add(Route)} 方法进行代理
 * 2. 自行代理时, 需要自行匹配请求路径, 并转发请求, 这样灵活度较高
 * 3. 可以给自行实现的 handler 类上添加 {@link Order} 注解, 用于控制优先级, 值越小越优先被匹配
 * </pre>
 *
 * @author lwm
 */
@Slf4j
@AllArgsConstructor
public class ProxyCollector implements Controllable {

    // 代理设置
    private final ProxySetting proxySetting;

    // 代理客户端
    private final ProxyClient proxyClient;

    @Override
    public void control(Router router) {
        It.of(proxySetting.getHttp()).filter(CollectionUtil::isNotEmpty).also(proxies -> {
            if (!proxySetting.isEnable()) {
                log.warn("Server Proxy is not enable, Please check it. See setting of ${server.proxy.enable}");
            }
            for (ProxyHttpSetting proxy : proxies) {
                PathUtil.Pathable path = PathUtil.of(proxy.getPrefixPath());
                if (!"*".equals(path.toString())) {
                    path = path.append("**");
                }
                router.proxy(path.toString(), new ProxyHandler(proxy, proxyClient));
            }
        });
    }

}
